package com.ygqh.baby.http;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Map;

import org.apache.log4j.Logger;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.HttpClient;
import com.foxinmy.weixin4j.http.HttpClientException;
import com.foxinmy.weixin4j.http.HttpHeaders;
import com.foxinmy.weixin4j.http.HttpMethod;
import com.foxinmy.weixin4j.http.HttpRequest;
import com.foxinmy.weixin4j.http.HttpResponse;
import com.foxinmy.weixin4j.http.URLParameter;
import com.foxinmy.weixin4j.http.apache.FormBodyPart;
import com.foxinmy.weixin4j.http.apache.HttpMultipartMode;
import com.foxinmy.weixin4j.http.apache.MultipartEntity;
import com.foxinmy.weixin4j.http.entity.FormUrlEntity;
import com.foxinmy.weixin4j.http.entity.HttpEntity;
import com.foxinmy.weixin4j.http.entity.StringEntity;
import com.foxinmy.weixin4j.http.factory.HttpClientFactory;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.exception.YgHttpException;

/**
 * 负责请求的执行
 * 
 * @see
 */
public class YgRequestExecutor {

	private static final Logger logger = Logger.getLogger(YgRequestExecutor.class);

	private final HttpClient httpClient;

	public YgRequestExecutor() {
		this.httpClient = HttpClientFactory.getInstance();
	}

	/**
	 * Post方法执行微信请求
	 * 
	 * @param url
	 *            请求URL
	 * @param body
	 *            参数内容
	 * @return 响应
	 * @throws WeixinException
	 */
	public YgResponse post(String url, String body) throws YgHttpException {
		HttpEntity entity = new StringEntity(body);
		HttpRequest request = new HttpRequest(HttpMethod.POST, url);
		request.setEntity(entity);
		return doRequest(request);
	}

	public YgResponse post(String url, HttpHeaders headers, String body) throws YgHttpException {
		HttpEntity entity = new StringEntity(body);
		HttpRequest request = new HttpRequest(HttpMethod.POST, url);
		request.setHeaders(headers);
		request.setEntity(entity);
		return doRequest(request);
	}
/*	public YgResponse post(String url, HttpHeaders headers, Map<String,String> bodys) throws YgHttpException, UnsupportedEncodingException {
		HttpRequest request = new HttpRequest(HttpMethod.POST, url);
		request.setHeaders(headers);
		if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            HttpEntity   formEntity = new  UrlEncodedFormEntity(nameValuePairList, "utf-8");
            request.setEntity( formEntity);
        }
		
		return doRequest(request);
	}*/

	/**
	 * Post方法执行请求
	 * 
	 * @param url
	 *            请求URL
	 * @param body
	 *            参数内容
	 * @return 响应
	 * @throws YgHttpException
	 */
	public YgResponse post(String url, Map<String, String> body) throws YgHttpException {
		HttpEntity entity = new FormUrlEntity(body);
		HttpRequest request = new HttpRequest(HttpMethod.POST, url);
		request.setEntity(entity);
		return doRequest(request);
	}

	/**
	 * Post方法执行请求，用于文件上传
	 * 
	 * @param url
	 *            请求URL
	 * @param bodyParts
	 *            文件内容
	 * @return 响应
	 * @throws YgHttpException
	 */
	public YgResponse post(String url, FormBodyPart... bodyParts) throws YgHttpException {
		MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8"));
		for (FormBodyPart bodyPart : bodyParts) {
			entity.addPart(bodyPart);
		}
		HttpRequest request = new HttpRequest(HttpMethod.POST, url);
		request.setEntity(entity);
		return doRequest(request);
	}

	/**
	 * Get方法执行请求
	 * 
	 * @param url
	 *            请求URL，如：https://api.weixin.qq.com/cgi-bin/token
	 * @param parameters
	 *            url上的参数，如:new URLParameter("appid",xxxxx)
	 * @return 响应
	 * @throws YgHttpException
	 */
	public YgResponse get(String url, URLParameter... parameters) throws YgHttpException {
		// always contain the question mark
		StringBuilder buf = new StringBuilder(url);
		if (parameters != null && parameters.length > 0) {
			buf.append("&").append(FormUrlEntity.formatParameters(Arrays.asList(parameters)));
		}
		HttpRequest request = new HttpRequest(HttpMethod.GET, buf.toString());
		return doRequest(request);
	}

	/**
	 * 执行请求
	 * 
	 * @param request
	 *            请求
	 * @return 响应
	 * @throws YgHttpException
	 */
	public YgResponse doRequest(HttpRequest request) throws YgHttpException {
		try {
			HttpResponse httpResponse = httpClient.execute(request);
			YgResponse response = new YgResponse(httpResponse);
			//handleResponse(response);
			return response;
		} catch (HttpClientException e) {
			throw new YgHttpException(e);
		}
	}

	/**
	 * handle the weixin response
	 * 
	 * @param response
	 *            请求响应
	 * @throws YgHttpException
	 */
	protected void handleResponse(YgResponse response) throws YgHttpException {
		Message result = response.getAsResult();
		if (Message.Type.success != result.getType()) {
			throw new YgHttpException(result.getCode() + "", result.getContent());
		}
	}

	public HttpClient getExecuteClient() {
		return httpClient;
	}

}
